// PictureBox.cpp : implementation file
//


#include "PictureBox.h"
#include <comdef.h>
#include "win-util.h"
// CPictureBox

IMPLEMENT_DYNAMIC(CPictureBox, CStatic)
CPictureBox::CPictureBox()
{
}

CPictureBox::~CPictureBox()
{
}


BEGIN_MESSAGE_MAP(CPictureBox, CStatic)
	ON_WM_PAINT()
END_MESSAGE_MAP()



// CPictureBox message handlers

void CPictureBox::ShowBitmap(CPaintDC *pdc) 
{
	//Create a device context to load the bitmap into
	CDC dcMem;
	dcMem.CreateCompatibleDC(pdc);

	//Get the Display area available
	CRect lRect;
	GetClientRect(lRect);
	lRect.NormalizeRect();
	int w, h;
	w = lRect.Width();
	h = lRect.Height();
	if(h > w)
	{
		h = w * (float)m_image.GetHeight() / m_image.GetWidth();
	}
	else
	{
		w = h * (float)m_image.GetWidth()/m_image.GetHeight();
	}

	//select the bitmap into compatible device context
	CBitmap* pOldBitmap = (CBitmap*)dcMem.SelectObject(m_image);
	//m_bmpBitmap.SetBitmapDimension(lRect.Width(),lRect.Height());
	pdc->SetStretchBltMode(HALFTONE);
	//copy & resize the window to the dialog window
	if (!pdc->StretchBlt(0, 0, w-1, h-1, &dcMem, 0, 0, m_image.GetWidth()-1, m_image.GetHeight()-1, SRCCOPY))
	{
		LastErrorMsg();
	}
}
void CPictureBox::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	RECT rect;
	GetClientRect(&rect);
	dc.FillSolidRect(&rect, RGB(255,255,255));

	if(!m_image.IsNull())
		ShowBitmap(&dc);
}

void CPictureBox::SetBitmap(::CString strBitmap)
{
	m_image.Destroy();
	HRESULT res = m_image.Load(strBitmap);
	if (res != S_OK) {
		AfxMessageBox(_com_error(GetLastError()).ErrorMessage(), MB_ICONSTOP);
    }
	else
	{
		Invalidate();
	}
}